package com.fms.sys.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fms.common.vo.Result;
import com.fms.sys.entity.BlogCategory;
import com.fms.sys.service.IBlogCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 博客分类控制器
 * </p>
 *
 * @author Jinfeng
 * @since 2024-05-05
 */
@RestController
@RequestMapping("/blog/category")
public class BlogCategoryController {

    @Autowired
    private IBlogCategoryService blogCategoryService;

    /**
     * 分页查询分类列表
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> getCategoryList(
            @RequestParam(value = "pageNo", defaultValue = "1") Long pageNo,
            @RequestParam(value = "pageSize", defaultValue = "10") Long pageSize,
            @RequestParam(value = "name", required = false) String name) {
        System.out.println("【分类接口】被调用");

        Page<BlogCategory> page = new Page<>(pageNo, pageSize);
        blogCategoryService.getCategoryList(page, name);

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());

        return Result.success(data);
    }

    /**
     * 新增分类
     */
    @PostMapping
    public Result<?> addCategory(@RequestBody BlogCategory category) {
        if (category.getName() == null || category.getName().trim().isEmpty()) {
            return Result.fail("分类名称不能为空");
        }
        blogCategoryService.addCategory(category);
        return Result.success("新增分类成功");
    }

    /**
     * 修改分类
     */
    @PutMapping
    public Result<?> updateCategory(@RequestBody BlogCategory category) {
        if (category.getName() == null || category.getName().trim().isEmpty()) {
            return Result.fail("分类名称不能为空");
        }
        blogCategoryService.updateCategory(category);
        return Result.success("修改分类成功");
    }

    /**
     * 删除分类
     */
    @DeleteMapping("/{id}")
    public Result<?> deleteCategory(@PathVariable("id") Long id) {
        blogCategoryService.deleteCategory(id);
        return Result.success("删除分类成功");
    }

    /**
     * 获取分类详情
     */
    @GetMapping("/{id}")
    public Result<BlogCategory> getCategoryById(@PathVariable("id") Long id) {
        BlogCategory category = blogCategoryService.getCategoryById(id);
        return Result.success(category);
    }
}
